#!/bin/bash

__disk_logfile="$TONE_CURRENT_RESULT_DIR/disksetup.log"

# return: nr_disk disk_type
parse_disk()
{
    local disk=$1
    nr_disk=${disk//[a-Z]}
    # Set default nr_disk to 1
    [ -n "$nr_disk" ] || nr_disk=1
    disk_type=${disk##[0-9]}
    disk_type=${disk_type,,}
}

# setup_disk_for disk nr_disk
# $1 canbe disk, null, brd, nfs3, nfs4, pmem, virtio_fs
setup_disk_fs()
{
    local disk="${1-disk}"
    local nr_disk="${2:-1}"
    local use_mounted="$3"
    local p_size="$4"

    if [ "${disk,,}" == "disk" ]; then
        # Process disk drive
        if [ -n "$TONE_DISK" ]; then
            disk_opt="--device '$TONE_DISK'"
        else
            disk_opt="--device disk"
        fi
    else
        disk_opt="--device '${disk,,}'"
    fi

    if [ -n "$p_size" ]; then
        size_opt="--size $p_size"
    elif [ -n "$disk_size" ]; then
        size_opt="--size $disk_size"
    fi

    if [ -n "$nr_disk" ]; then
        part_opt="--partitionnumber $nr_disk"
    fi

    if [ -n "$fs" ]; then
        # Process memory disk
        fs_opt="--filesystem $fs"
    fi

    if [ -n "$mkfsopt" ]; then
        mkfs_opt="--mkfsopt '$mkfsopt'"
    else
        mkfs_opt=""
    fi

    if [ -n "$mountopt" ]; then
        mount_opt="--mountopt '-o $mountopt'"
    else
        mount_opt=""
    fi

    if [ -n "$use_mounted" ]; then
        use_mounted_opt="--usemounted"
    else
        use_mounted_opt=""
    fi

    local cmd="$TONE_ROOT/bin/disksetup.py $disk_opt $size_opt $part_opt $fs_opt $mkfs_opt $mount_opt $use_mounted_opt"
    echo $cmd
    eval $cmd > $__disk_logfile
    ret=$?
    [[ $ret == 0 ]] || exit

    cat $__disk_logfile | awk 'NR>1 {print p}{p=$0}'
    restoredev=$(cat $__disk_logfile | tail -1)
    echo $restoredev > $__disk_logfile
}

__get_restoredev()
{
    local ret=""
    [ -f $__disk_logfile ] && ret=$(cat $__disk_logfile)
    [ -n "$ret" ] && {
        ret="--restoredev '$ret'"
        echo $ret
        return 0
    }
    return 1
}

umount_fs()
{
    eval "$TONE_ROOT"/bin/disksetup.py --umount $(__get_restoredev)
}

clean_disk()
{
    eval "$TONE_ROOT"/bin/disksetup.py --cleandisk $(__get_restoredev)
    ret=$?
    [ "$ret" == 0 ] && rm -rf $__disk_logfile
}

get_mount_points()
{
    eval "$TONE_ROOT"/bin/diskinfo.py $(__get_restoredev) data_mountpoints
}

get_dev_partition()
{
    eval "$TONE_ROOT"/bin/diskinfo.py $(__get_restoredev) data_partition
}

get_test_disks()
{
    eval "$TONE_ROOT"/bin/diskinfo.py $(__get_restoredev) data_disk
}

